<template>
  <div class="app-container calendar-list-container">

    <el-tabs v-model="activeName" @tab-click="handleTabsClick">
      <el-tab-pane label="基本信息" name="first">
        <el-card class="box-card">
          <el-button v-if="saveStatus=='create'" type="primary" icon="el-icon-edit" @click="create">保存信息</el-button>
          <el-button v-else type="primary" icon="el-icon-edit" @click="update">保存信息</el-button>
          <el-button v-if="saveStatus=='create'" type="primary" icon="el-icon-edit">保存信息</el-button>
          <el-button type="danger" @click="handleCancel">返回列表</el-button>
        </el-card>
        <el-card class="box-card goods" style="width: 100%;margin-top: 2px">
          <el-form ref="goodsForm" :rules="rules" :model="goodsForm" label-width="120px">

            <el-row type="flex" class="row-bg">
              <el-col :span="18">
                <globalFormItem :key="formKey" :config="globalConfig" label="商品主图"  v-model="goodsForm.logo"  prop="logo" type="img"></globalFormItem>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="9">
                <el-form-item label="商品名称:" prop="goodsName">
                  <el-input v-model="goodsForm.goodsName" placeholder="请输入商品名称"
                            suffix-icon="el-icon-edit el-input__icon"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="9">
                <globalFormItem :key="formKey" :config="globalConfig" label="商品品牌:" v-model="goodsForm.brandId"
                                prop="brandId" placeholder="请选择品牌" :props="{ checkStrictly: true }"
                                :load="brandRemoteUrl" type="select"></globalFormItem>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">

              <el-col :span="18">
                <el-form-item label="商品标签:" prop="keywords">

                  <el-button v-if="!mKeywordVisible" class="button-new-keyword" type="primary" @click="showInput">+ 设置
                  </el-button>
                  <el-input v-else ref="mKeywordInput" v-model="mKeyword" class="input-new-keyword"
                            @keyup.enter.native="handleInputConfirm"/>
                  <el-tag v-for="item in goodsForm.keywords" :key="item" closable type="primary"
                          @close="handleClose(item)"
                          v-if="item== '' ? false : true">
                    {{'#' +item }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="9">
                <globalFormItem :key="formKey" :config="globalConfig" label="上架状态:" v-model="goodsForm.onSale"
                                prop="onSale"
                                placeholder="请选择上架状态" type="select"></globalFormItem>
              </el-col>

              <el-col :span="9">
                <globalFormItem :key="formKey" :config="globalConfig" label="商品分类:" v-model="goodsForm.categoryId"
                                prop="categoryId" placeholder="请选择分类"
                                :props="{ checkStrictly: true }"
                                :load="casDataUrl" type="cas"></globalFormItem>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="9">
                <globalFormItem :key="formKey" :config="globalConfig" label="商品供应商:" v-model="goodsForm.supplierId"
                                prop="supplierId" placeholder="请选择供应商" :props="{ checkStrictly: true }"
                                :load="supplierRemoteUrl" type="select"></globalFormItem>
              </el-col>

              <el-col :span="9">
                <el-form-item label="商品现金价:" prop="retailPrice">
                  <el-input v-model="goodsForm.retailPrice" oninput="value=value.replace(/[^0-9.]/g,'')"
                            placeholder="请输入商品现金价" suffix-icon="el-icon-edit el-input__icon" type="number"
                            clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="9">
                <el-form-item label="商品供货价:" prop="counterPrice">
                  <el-input v-model="goodsForm.counterPrice" oninput="value=value.replace(/[^0-9.]/g,'')"
                            placeholder="请输入商品供货价" suffix-icon="el-icon-edit el-input__icon" type="number"
                            clearable></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="9">
                <el-form-item label="商品对比价:" prop="contrastPrice">
                  <el-input v-model="goodsForm.contrastPrice" oninput="value=value.replace(/[^0-9.]/g,'')"
                            placeholder="请输入商品对比价" suffix-icon="el-icon-edit el-input__icon" type="number"
                            clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="18">
                <el-form-item label="轮  播  图:" prop="gallery">
                  <el-upload
                    :action="uploadPath"
                    :headers="headers"
                    :limit="8"
                    :file-list="tempGalleryList"
                    :on-exceed="uploadOnExceed"
                    :on-success="uploadOnSuccess"
                    :on-remove="uploadOnRemove"
                    multiple
                    accept=".jpg,.jpeg,.png,.gif"
                    list-type="picture-card"
                    :on-preview="uploadOnExceedPreview">
                    <i class="el-icon-plus"/>
                  </el-upload>

                </el-form-item>
              </el-col>
            </el-row>

            <el-row type="flex" class="row-bg">
              <el-col :span="18">
                <el-form-item label="轮播图排序">
                  <draggable v-model="goodsForm.gallery" @change="uploadOnExceedDrag">
                    <transition-group>
                      <el-image
                        v-for="(item,index) in goodsForm.gallery"
                        style="width: 80px; height: 80px; padding: 2px; margin: 5px; border: 1px solid #f4f4f4;"
                        :src="item"
                        :key="index"
                        :title="removeTip"></el-image>
                    </transition-group>
                  </draggable>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="规格属性" name="second">
        <el-card class="box-card">
          <el-button type="primary" icon="el-icon-edit" @click="handleSpecificationFormOpen">添加规格</el-button>
          <el-button v-if="saveStatus=='create'" type="primary" icon="el-icon-edit" @click="create">保存信息</el-button>
          <el-button v-else type="primary" icon="el-icon-edit" @click="update">保存信息</el-button>
          <el-button type="danger" @click="handleCancel">返回列表</el-button>
        </el-card>
        <el-card class="box-card" style="width: 100%;margin-top: 2px">
          <!--      <el-form ref="goodsInfo" :rules="rules" :model="specificationForm">-->
          <!--      </el-form>-->
          <el-table :data="specificationsList">
            <el-table-column property="specificationName" label="规格名" width="150" style="font-weight:bold"/>
            <el-table-column property="optionsNames" label="属性值" width="250" align="center">
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.optionsNames" :key="item" style="font-weight:bold" closable
                        @close="handleSpecificationDeleteTag(scope.row,item)">
                  {{ item }}
                </el-tag>
                <el-input v-if="scope.row.specInputVisible"
                          v-model="specInputValue" class="input-new-keyword"
                          @keyup.enter.native="handleInputTagConfirm(scope.row,specInputValue)"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="350" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button v-if="!scope.row.specInputVisible" type="primary" icon="el-icon-edit"
                           @click="scope.row.specInputVisible=!scope.row.specInputVisible">+ 新增
                </el-button>
                <el-button type="danger" @click="handleSpecificationUpdate(scope.row)">修改</el-button>
                <el-button type="danger" @click="handleSpecificationDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-dialog :visible.sync="specVisible" title="设置规格" width="35%">
            <el-form ref="specificationForm" :rules="rules" :model="specificationForm" status-icon label-position="left"
                     label-width="60px"
                     style="width: 300px; margin-left:100px;">
              <el-form-item label="规格名" prop="specification">
                <el-input v-model="specificationForm.specificationName" suffix-icon="el-icon-edit el-input__icon"/>
              </el-form-item>
              <el-form-item>
                <el-button class="button-new-keyword" type="success" @click="addSpecification">+ 可选项</el-button>
              </el-form-item>
              <div class="title">
                <span>可选项</span>
              </div>
              <el-form-item v-for="(item, index) in specificationForm.optionsNames" :key="index"
                            :rules="{required: true, message: '规格名不能为空', trigger: 'blur'}">

                <el-input v-model="specificationForm.optionsNames[index]"
                          suffix-icon="el-icon-edit el-input__icon">

                  <el-button slot="append" @click.prevent="removeSpecification(item)">删除</el-button>
                </el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="handleSpecificationClose">取消</el-button>
              <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
            </div>
          </el-dialog>
        </el-card>
        <el-card class="box-card" style="width: 100%;margin-top: 10px">
          <h3>SKU信息</h3>
          <!--      <el-form ref="goodsInfo" :rules="rules" :model="skuForm">-->
          <!--      </el-form>-->
          <el-table :data="skuList" :key="key">
            <el-table-column property="specificationNames" label="SKU属性" width="250">
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.specificationNames" :key="item" :title="item">
                  {{ item }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column :key="key" property="picUrl" width="120" label="图片" align="center">
              <template slot-scope="scope">
                <globalGeneralTemplate :key="key" :config="globalConfig" v-model="scope.row.picUrl"
                                       type="img"></globalGeneralTemplate>
              </template>
            </el-table-column>

            <el-table-column :key="key" property="counterPrice" width="120" label="供货价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.counterPrice" placeholder="0.00" style="width: 100%;font-weight:bold"
                          suffix-icon="el-icon-edit el-input__icon" type="number"/>
              </template>
            </el-table-column>
            <el-table-column :key="key" property="guidedPrice" width="120" label="指导价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.guidedPrice" placeholder="0.00" style="width: 100%;font-weight:bold"
                          suffix-icon="el-icon-edit el-input__icon" type="number"/>
              </template>
            </el-table-column>
            <el-table-column :key="key" property="retailPrice" width="120" label="现金价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.retailPrice" placeholder="0.00" style="width: 100%;font-weight:bold"
                          suffix-icon="el-icon-edit el-input__icon" type="number"/>
              </template>
            </el-table-column>
            <el-table-column :key="key" property="contrastPrice" width="120" label="对比价格" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.contrastPrice" placeholder="0.00" style="width: 100%;font-weight:bold"
                          suffix-icon="el-icon-edit el-input__icon" type="number"/>
              </template>
            </el-table-column>
            <el-table-column :key="key" align="center" label="操作" width="100" class-name="small-padding fixed-width">
              <template slot-scope="scope" align="center">
                <el-button type="primary" icon="el-icon-edit" @click="handleSkuFormShow(scope.row)">设置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-dialog :visible.sync="skuVisible" title="SKU设置" width="35%">
            <el-form ref="skuForm" :model="skuForm" status-icon label-position="left" label-width="80px"
                     style="margin-left:50px;">
              <el-form-item label="SKU  属  性" prop="specifications">
                <el-tag v-for="item in skuForm.specificationNames" :key="item">
                  {{ item }}
                </el-tag>
              </el-form-item>

              <globalFormItem :key="formKey" :config="globalConfig" label="图片" v-model="skuForm.picUrl" prop="picUrl"
                              type="img"></globalFormItem>
              <globalFormItem :key="formKey" :config="globalConfig" label="供货价格" v-model="skuForm.counterPrice"
                              prop="counterPrice" placeholder="0.00" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></globalFormItem>
              <globalFormItem :key="formKey" :config="globalConfig" label="指导价格" v-model="skuForm.guidedPrice"
                              prop="guidedPrice" placeholder="0.00" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></globalFormItem>
              <globalFormItem :key="formKey" :config="globalConfig" label="现金价格" v-model="skuForm.retailPrice"
                              prop="retailPrice" placeholder="0.00" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></globalFormItem>
              <globalFormItem :key="formKey" :config="globalConfig" label="对比价格" v-model="skuForm.contrastPrice"
                              prop="contrastPrice" placeholder="0.00" suffix-icon="el-icon-edit el-input__icon"
                              type="number"></globalFormItem>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="handleSkuFormCancel">取消</el-button>
              <el-button type="primary" @click="handleSkuFormEdit">确定</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="third">
        <el-card class="box-card">
          <el-button v-if="saveStatus=='create'" type="primary" icon="el-icon-edit" @click="create">保存信息</el-button>
          <el-button v-else type="primary" icon="el-icon-edit" @click="update">保存信息</el-button>
          <el-button type="danger" @click="handleCancel">返回列表</el-button>
        </el-card>
        <el-card class="box-card goods" style="width: 100%;margin-top: 2px">
          <el-row type="flex" class="row-bg">
            <el-col :span="14">
              <el-card class="box-card" style="width: 100%;height: 100%">
                <globalQuillEditor :key="formKey"  v-model="goodsForm.introduction"></globalQuillEditor>
              </el-card>
            </el-col>

            <el-col :span="10">
              <div class="popContainer">
                <el-card class="box-card" style="width: 100%;height: 100%;padding: 0">
                  <div class="iphone">
                    <div class="iphone-top">
                      <span class="camera"></span>
                      <span class="sensor"></span>
                      <span class="speaker"></span>
                    </div>
                    <div class="top-bar"></div>
                    <div class="iphone-screen">
                      <div v-html="htmlGeometric()" style="height:750px;overflow-y:auto"/>
                    </div>
                    <div class="buttons">
                      <span class="on-off"></span>
                      <span class="sleep"></span>
                      <span class="up"></span>
                      <span class="down"></span>
                    </div>
                    <div class="bottom-bar"></div>
                    <div class="iphone-bottom">
                      <span></span>
                    </div>
                  </div>
                </el-card>
              </div>
            </el-col>
          </el-row>
        </el-card>

      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="uploadDialogVisible">
      <img width="100%" :src="uploadPreviewUrl" alt="">
    </el-dialog>
  </div>

</template>

<style scoped>
  .el-card__body {
    padding: 10px !important;
  }

  .el-card {
    padding-top: 10px;
  }

  .el-tag {
    margin-top: 10px;
    margin-left: 10px;
  }

  .goods .el-form {
    margin-top: 20px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .el-form-item .el-input {
    width: 320px;
  }

  .el-form-item .el-select {
    width: 320px;
  }

  .el-form-item .el-cascader {
    width: 320px;
  }

  .popContainer {
    position: fixed;
    top: 0;
    left: 64%;
    right: 0;
    bottom: 0;
    width: 46%;
    height: 100%;
    z-index: 3000;
    background: white;
  }
</style>

<script scoped>
  import '../../../styles/phone/css/style.css'

  import { fetchList, getObj, addObj, putObj, delObj, casObj } from '@/api/supplier/goods'
  import { remoteData as brandRemoteData } from '@/api/supplier/brand'
  import { remoteData as supplierRemoteData } from '@/api/supplier/supplier'
  import { casObj as categoryCasObj } from '@/api/supplier/category'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  import { mapGetters } from 'vuex'
  import { globalNotify, globalWarning } from '@/util/notifyUtils'  //弹窗
  import { getToken } from '@/util/auth'
  import globalSearchTemplate from '@/components/global-el-search-template'
  import globalTableColumn from '@/components/global-el-table-column'
  import globalFormItem from '@/components/global-el-form-item'
  import globalGeneralTemplate from '@/components/global-el-general-template'
  import globalQuillEditor from '@/components/global-quill-editor'
  import uuid from 'uuid'
  import { cloneObject } from '../../../util/casUtils'
  import { uploadPath } from '@/api/storage'  //上传图片

  export default {
    name: 'add',
    components: { globalSearchTemplate, globalTableColumn, globalFormItem, globalGeneralTemplate, globalQuillEditor },
    directives: {
      waves
    },
    data() {
      return {
        globalConfig: {
          module: ['supplier'],
          componentName: ['goods']
        },
        list: null,
        total: null,
        listLoading: true,
        uploadPath,
        listQuery: {
          page: 1,
          limit: 20,
          'startTime': undefined,
          'endTime': undefined,
          'brandName': undefined
        },
        rules: {},
        goodsForm: {
          'onSale': 1,
          'categoryId': undefined,
          'brandId': undefined,
          'supplierId': undefined,
          'retailPrice': undefined,
          'contrastPrice': undefined,
          'counterPrice': undefined,
          'introduction': '',
          'memo': undefined,
          'monthHits': undefined,
          'monthHitsDate': undefined,
          'monthSales': undefined,
          'monthSalesDate': undefined,
          'keywords': [],
          'gallery': [],
          'top': undefined,
          'goodsName': undefined
        },
        specificationForm: {
          'key': (new Date()).valueOf(),
          'specificationName': undefined,
          'optionsNames': [],
          'optionsValues': [],
          'goodsId': undefined,
          'specInputVisible': false
        },
        skuForm: {
          'key': (new Date()).valueOf(),
          'goodsId': undefined,
          'specificationValues': [],
          'retailPrice': 0.00,
          'contrastPrice': 0.00,
          'counterPrice': 0.00,
          'guidedPrice': 0.00,
          'specificationNames': [],
          'picUrl': undefined
        },
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        key: '',
        formKey: '',
        tableFormKey: '',
        mKeyword: undefined,
        mKeywordVisible: false,
        casDataUrl: casObj,
        brandRemoteUrl: brandRemoteData,
        categoryCasUrl: categoryCasObj,
        supplierRemoteUrl:supplierRemoteData,
        specVisible: false,
        specificationsList: [],
        specFormSize: -1,
        skuList: [],
        skuVisible: false,
        specInputVisible: false,
        specInputValue: undefined,
        tableKey: 0,
        galleryDragList: [],
        uploadPreviewUrl: undefined,
        uploadDialogVisible: false,
        removeTip: '拖动排序',
        activeName: 'first',
        dialogDetailsVisible: false,
        htmlIntroduction: undefined,
        saveStatus: 'create',
        tempGalleryList:[]
      }
    },
    computed: {
      ...mapGetters([
        'permissions'
      ])
    },
    filters: {},
    created() {
      Array.prototype.unique = function(a) {
        return function() {
          return this.filter(a)
        }
      }(function(a, b, c) {
        return c.indexOf(a, b + 1) < 0
      })

      let goodsId = this.$route.query.goodsId// 列表页查询参数暂存
      if(goodsId!=undefined)
          this.read(goodsId)
    },
    methods: {
      handleCancel() {
        this.$store.commit("DEL_CURRENT_TAG", null);
        this.$router.push({path: '/supplier/goods'})
      },
      create() {
        let params = {
          goods: this.goodsForm,
          goodsSkuList: this.skuList,
          goodsSpecificationList: this.specificationsList
        }

        addObj(params)
          .then((response) => {
              if (response.data.code == 0) {
                this.saveStatus = 'update'
                this.getGoodsForm = response.data.data
              }
              globalNotify(this, response)
            }
          )
      },
      update() {
        let params = {
          goods: this.goodsForm,
          goodsSkuList: this.skuList,
          goodsSpecificationList: this.specificationsList
        }

        putObj(params).then((response) => {
            globalNotify(this, response)
          }
        )
      },
      read(id) {
        this.saveStatus = 'update'
        getObj(id).then(response => {
          if (response.data.code == 0) {

            this.goodsForm = Object.assign({}, response.data.data.goods)
            this.goodsForm.gallery.forEach(item=>{
              this.tempGalleryList.push({
                url: item
              })
            })
            this.skuList = response.data.data.goodsSkuList
            response.data.data.goodsSpecificationList.forEach(item => {
              item.specInputVisible = false
            })
            this.specificationsList = response.data.data.goodsSpecificationList
            this.refreshForm()
            this.refreshTable()
          }
        })
      },
      htmlGeometric() {
        //正则匹配不含style="" 或 style='' 的img标签
        var regexStyle = new RegExp('(i?)(\<img)(?!(.*?style=[\'"](.*)[\'"])[^\>]+\>)', 'gmi')
        var regexWidth = /width=\"([^\"]*?)\"/i

        this.htmlIntroduction = cloneObject(this.goodsForm.introduction)

        let temp = this.htmlIntroduction.replace(/<img[^>]*>/gi, function(match, capture) {
          var s = match.match(regexWidth)
          var room = undefined
          if (s != null && s.length > 0) {
            var widthRatio = parseInt(s[1].replace('px', '')) / (document.body.clientWidth * (14 / 24 - 0.1217))
            room = document.body.clientWidth * 0.19736 * widthRatio
          }
          if (room != undefined) {
            //给不含style="" 或 style='' 的img标签加上style=""
            match = match.replace(regexStyle, '$2 style="height:auto;" $3')
            return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, 'style="max-width:' + room + 'px;height:auto;"')
          }
        })

        return temp
      },
      handleTabsClick(tab, event) {
        if (this.activeName == 'third') {
          this.dialogDetailsVisible = !this.dialogDetailsVisible
        } else {
          this.dialogDetailsVisible = false
        }
      },
      getHeaders() {
        var headers = {
          Authorization: 'Bearer ' + getToken()
        }
        return headers
      },
      getBaseUrl() {
        return uploadPath
      },
      uploadOnSuccess(response, file, fileList) {
        this.tempGalleryList=fileList
        this.goodsForm.gallery.push(response.data.url)
      },
      uploadOnRemove: function(file, fileList) {
        this.tempGalleryList = fileList
        let hasIndex = -1
        this.goodsForm.gallery.findIndex((item, index) => {
          var url
          if (file.response === undefined) {
            url = file.url
          } else {
            url = file.response.data.url
          }

          if (item == url) {
            hasIndex = index
          }
        })

        if (hasIndex != -1) {
          this.goodsForm.gallery.splice(hasIndex, 1)
        }
      },
      uploadOnExceedDrag(t) {

      },
      uploadOnExceedPreview(file) {
        this.uploadPreviewUrl = file.url
        this.uploadDialogVisible = true
      },
      uploadOnExceed: function() {
        globalWarning(this, '上传文件个数超出限制')
      },
      refreshTable() {
        this.key = new Date().getTime()
      },
      refreshForm() {
        this.formKey = new Date().getTime()
      },
      refreshTableForm() {
        this.tableFormKey = new Date().getTime()
      },
      handleClose(val) {
        this.goodsForm.keywords.splice(this.goodsForm.keywords.indexOf(val), 1)
      },
      handleInputConfirm() {
        const keyword = this.mKeyword
        if (keyword != '' && keyword != undefined) {
          this.goodsForm.keywords.push(keyword)
        }
        this.mKeywordVisible = false
        this.mKeyword = undefined
      },
      showInput() {
        this.mKeywordVisible = true
        this.$nextTick(_ => {
          this.$refs.mKeywordInput.$refs.input.focus()
        })
      },
      handleSpecificationFormOpen() {
        this.specVisible = !this.specVisible
      },
      resetSpecificationForm() {
        this.specificationForm = {
          specificationName: undefined,
          optionsNames: [],
          optionsValues: [],
          key: (new Date()).valueOf(),
          specInputVisible: false
        }
      },
      handleSpecificationClose() {
        this.specVisible = !this.specVisible
        this.resetSpecificationForm()
      },
      handleSpecificationAdd() {
        if (this.specificationForm.specificationName == '' || this.specificationForm.specificationName == undefined) {
          globalWarning(this, '规格名称不能为空')
          return
        }

        //属性名称-值对应集合
        const valueMap = new Map()
        this.specificationsList.forEach(spec => {
          if (spec.key != this.specificationForm.key) {
            spec.optionsNames.forEach((item, index) => {
              valueMap.set(item, spec.optionsValues[index])
            })
          }
        })

        //进行属性重复判断
        var repeat = false

        if (this.specificationForm.optionsNames.length == 0) {
          repeat = true
          globalWarning(this, '规格属性必填')
        }

        this.specificationForm.optionsNames.forEach(item => {
          if (item == undefined || item == '') {
            repeat = true
            globalWarning(this, '属性名称不能为空')
            return
          }
          if (valueMap.get(item)) {
            repeat = true
            globalWarning(this, '【' + item + '】属性名称不能重复')
            return
          }
        })

        if (this.specificationForm.optionsNames.length != this.specificationForm.optionsNames.unique().length) {
          globalWarning(this, '规格属性名称不能重复')
          repeat = true
        }
        //重复 就返回，不做处理
        if (repeat) {
          return false
        }

        let hasIndex = -1
        this.specificationsList.findIndex((item, index) => {
          if (item.key == this.specificationForm.key) {
            hasIndex = index
          }
        })

        if (hasIndex != -1) {
          this.specificationsList.splice(hasIndex, 1, cloneObject(this.specificationForm))
        } else {
          this.specificationsList.push(cloneObject(this.specificationForm))
        }

        //进行SKU 处理
        this.descartesToGreatSku()
        this.resetSpecificationForm()
        this.specVisible = !this.specVisible
      },
      handleSpecificationUpdate(row) {
        this.specificationForm = cloneObject(row)
        this.specFormSize = row.optionsNames.length
        this.specVisible = true
      },
      handleSpecificationDelete(row) {
        const index = this.specificationsList.indexOf(row)
        this.specificationsList.splice(index, 1)
        this.descartesToGreatSku()
      },
      handleSpecificationDeleteTag(row, tag) {
        const rowIndex = this.specificationsList.indexOf(row)
        const tagIndex = this.specificationsList[rowIndex].optionsNames.indexOf(tag)
        if (this.specificationsList[rowIndex].optionsNames.length > 1) {
          this.specificationsList[rowIndex].optionsNames.splice(tagIndex, 1)
          this.specificationsList[rowIndex].optionsValues.splice(tagIndex, 1)
        } else {
          this.specificationsList.splice(rowIndex, 1)
        }

        this.descartesToGreatSku()
      },
      handleInputTagConfirm(row, tag) {

        if (tag == undefined || tag == '') {
          row.specInputVisible = false
          return
        }

        const rowIndex = this.specificationsList.indexOf(row)
        const tagIndex = this.specificationsList[rowIndex].optionsNames.indexOf(tag)
        if (tagIndex != -1) {
          globalWarning(this, '【' + tag + '】属性名称不能重复')
          return
        }
        this.specificationsList[rowIndex].optionsNames.push(tag)
        this.specificationsList[rowIndex].optionsValues.push(uuid.v4().toString())
        row.specInputVisible = false
        this.specInputValue = undefined

        this.descartesToGreatSku()
      },
      addSpecification() {
        if (this.specificationForm.specificationName == '' || this.specificationForm.specificationName == undefined) {
          this.$message({
            type: 'warning',
            message: '规格名称不能为空'
          })
          return
        }
        this.specificationForm.optionsNames.push('')
        this.specificationForm.optionsValues.push(uuid.v4().toString())
      },
      removeSpecification(item) {
        var index = this.specificationForm.optionsNames.indexOf(item)
        if (index !== -1) {
          this.specificationForm.optionsNames.splice(index, 1)
          this.specificationForm.optionsValues.splice(index, 1)
        }
      },
      handleSkuFormShow(row) {
        this.skuForm = cloneObject(row)
        this.refreshForm()
        this.skuVisible = true
      },
      handleSkuFormCancel() {
        this.skuForm = {
          'key': (new Date()).valueOf(),
          'goodsId': undefined,
          'specificationValues': [],
          'retailPrice': 0.00,
          'contrastPrice': 0.00,
          'counterPrice': 0.00,
          'guidedPrice': 0.00,
          'specificationNames': [],
          'picUrl': undefined
        }
        this.skuVisible = !this.skuVisible
        this.refreshForm()
      },
      handleSkuFormEdit() {
        let hasIndex = -1
        this.skuList.findIndex((item, index) => {
          if (item.key == this.skuForm.key) {
            hasIndex = index
          }
        })

        if (hasIndex != -1) {
          this.skuList.splice(hasIndex, 1, this.skuForm)
        }

        this.skuForm = {
          'key': (new Date()).valueOf(),
          'goodsId': undefined,
          'specificationValues': [],
          'retailPrice': 0.00,
          'contrastPrice': 0.00,
          'counterPrice': 0.00,
          'guidedPrice': 0.00,
          'specificationNames': [],
          'picUrl': undefined
        }
        this.skuVisible = !this.skuVisible
      },
      includes(arr1, arr2) {
        return arr2.every(val => arr1.includes(val))
      },
      descartes(array) {

        if (array.length < 2) return array[0] || []

        return [].reduce.call(array, function(col, set) {
          var res = []
          col.forEach(function(c) {
            set.forEach(function(s) {
              var t = [].concat(Array.isArray(c) ? c : [c])
              t.push(s)
              res.push(t)
            })
          })
          return res
        })
      },
      descartesToGreatSku() {
        if (this.specificationsList.length == 0) {
          this.skuList = []
          return
        }

        //属性名称-值对应集合
        const valueMap = new Map()
        //规格总集合
        let allNameList = [], allValueList = []
        //组建临时存在规格
        this.specificationsList.forEach(spec => {
          allNameList.push(spec.optionsNames)
          allValueList.push(spec.optionsValues)
          spec.optionsNames.forEach((item, index) => {
            valueMap.set(item, spec.optionsValues[index])
          })
        })

        console.log('optionsNames', valueMap)
        //笛卡尔积生成sku组合,进行排序，防止更新位置不一致
        var tempNameDescartes = this.descartes(allNameList.sort())

        var tempSkuList = []
        //排序
        try {
          //对应原规格的数据。没有的就增加规格
          let i = 0
          tempNameDescartes.forEach((dsItem, dsIndex) => {
            let isHas = false
            dsItem = (dsItem instanceof Array) ? dsItem : [dsItem]
            var tempValue = []
            dsItem.forEach(val => {
              tempValue.push(valueMap.get(val))
            })

            this.skuList.forEach(sku => {
              const tempSku = {
                id: sku.id,
                key: (new Date()).valueOf() + i++,
                goodsId: sku.goodsId,
                retailPrice: sku.retailPrice,
                contrastPrice: sku.contrastPrice,
                counterPrice: sku.counterPrice,
                guidedPrice: sku.guidedPrice,
                specificationNames: dsItem,
                specificationValues: tempValue,
                picUrl: sku.picUrl
              }

              //无论是新增属性 还是减属性 ,说明规格存在过，进行一个更新
              if (this.includes(dsItem, sku.specificationNames) || this.includes(sku.specificationNames, dsItem)) {
                if (!isHas) {
                  isHas = true
                  tempSkuList.push(tempSku)
                }
              }
            })

            if (tempSkuList.length == tempNameDescartes.length) {
              throw 'continue'
            }

            if (!isHas) {
              tempSkuList.push(
                {
                  id: undefined,
                  key: (new Date()).valueOf() + i++,
                  goodsId: undefined,
                  retailPrice: this.skuForm.retailPrice,
                  contrastPrice: this.skuForm.contrastPrice,
                  counterPrice: this.skuForm.counterPrice,
                  guidedPrice: this.skuForm.guidedPrice,
                  specificationNames: dsItem,
                  specificationValues: tempValue,
                  picUrl: this.skuForm.picUrl
                })
            }
          })
        } catch (e) {

        }
        console.log('tempSkuList', tempSkuList)
        this.skuList = []
        tempSkuList.forEach(val => {

          this.skuList.push(val)
        })
        this.skuList.sort()
        this.refreshTable()
      }
    }
  }
</script>
